package com.ilink.teacherservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ilink.ilinkapi.dto.teacher.UpdateJsonStatusRequest;
import com.ilink.teacherservice.entity.PO.study.tree.JsonEntity;
import com.ilink.teacherservice.entity.PO.study.tree.JsonTagEntity;
import com.ilink.teacherservice.entity.PO.study.tree.StudyTreeJsonNodeStatus;
import com.ilink.teacherservice.entity.PO.study.tree.TagEntity;
import com.ilink.teacherservice.mapper.study.tree.StudyTreeJsonMapper;
import com.ilink.teacherservice.mapper.study.tree.StudyTreeJsonNodeStatusMapper;
import com.ilink.teacherservice.mapper.study.tree.StudyTreeJsonTagMapper;
import com.ilink.teacherservice.mapper.study.tree.StudyTreeTagMapper;
import com.ilink.teacherservice.service.StudyTreeJsonService;
import com.ilink.ilinkcommon.utils.UserContext;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@RequiredArgsConstructor
public class StudyTreeJsonServiceImpl implements StudyTreeJsonService {

    private final StudyTreeJsonMapper studyTreeJsonMapper;

    private final StudyTreeTagMapper studyTreeTagMapper;

    private final StudyTreeJsonTagMapper studyTreeJsonTagMapper;

    private final StudyTreeJsonNodeStatusMapper studyTreeJsonNodeStatusMapper;

    public List<String> getAllTags() {
        return studyTreeTagMapper.getAllTags();
    }

    public List<TagEntity> getCommonTags() { return studyTreeTagMapper.getCommonTags(); }

    public List<JsonEntity> getJsonsByTagsAndPagination(List<String> tagNames,String keyword, int page, int size) {
        QueryWrapper<JsonEntity> queryWrapper = new QueryWrapper<>();

        // 如果tagNames不为空且不为空列表，则进行标签筛选
        if (tagNames != null && !tagNames.isEmpty()) {
            // 先根据tagName获取对应的tagId列表
            List<Long> tagIds = studyTreeTagMapper.selectList(
                    new QueryWrapper<TagEntity>().in("tag_name", tagNames)
            ).stream().map(TagEntity::getTagId).collect(Collectors.toList());

            // 如果没有找到任何tagId，直接返回空列表
            if (tagIds.isEmpty()) {
                return Collections.emptyList();
            }

            // 根据获取到的tagId，在jsonTag表中查找对应的jsonId
            List<Long> jsonIds = studyTreeJsonTagMapper.selectList(
                    new QueryWrapper<JsonTagEntity>().in("tag_id", tagIds)
            ).stream().map(JsonTagEntity::getJsonId).collect(Collectors.toList());

            // 如果筛选出的jsonIds为空，直接返回空列表
            if (jsonIds.isEmpty()) {
                return Collections.emptyList();
            }

            // 根据json_id列表添加查询条件
            queryWrapper.in("id", jsonIds);
        }

        // 如果关键词不为空，则在 name, description, jsonContent 中查找
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper ->
                    wrapper.like("name", keyword)
                            .or().like("description", keyword)
                            .or().like("json_content", keyword)
            );
        }

        // 创建分页请求
        Page<JsonEntity> pageRequest = new Page<>(page, size);

        // 执行分页查询
        return studyTreeJsonMapper.selectPage(pageRequest, queryWrapper).getRecords();
    }


    /**
     * @Author 郑千鹤
     * @Description //获取当前用户该json技能树的状态，如果没有记录则创建一个新的
     * @Date 17:58 2024/9/16
     * @Param [id]
     * @return com.ilink.teacherservice.entity.PO.tree.JsonEntity
     **/
    @Override
    public JsonEntity getJsonById(Long id) {
        JsonEntity jsonEntity=studyTreeJsonMapper.selectById(id);
        String userId = UserContext.getUserId();
        log.info("userId: " + userId);
        String jsonStatus=studyTreeJsonNodeStatusMapper.findJsonStatusByUserIdAndJsonId(userId, id);
        // 如果查询到的 jsonStatus 为空，则插入新记录
        if (jsonStatus == null) {
            // 创建 StudyTreeJsonNodeStatus 对象，并插入新的记录
            StudyTreeJsonNodeStatus nodeStatus = new StudyTreeJsonNodeStatus();
            nodeStatus.setId(UUID.randomUUID().toString()); // 生成随机 ID
            log.info( "uuid: " +nodeStatus.getId());
            nodeStatus.setUserId(userId); // 设置用户ID
            nodeStatus.setJsonId(jsonEntity.getId()); // 使用 JsonEntity 的 ID
            nodeStatus.setJsonStatus(jsonEntity.getJsonContent()); // 使用 JsonEntity 的 jsonContent 作为 jsonStatus

            try {
                studyTreeJsonNodeStatusMapper.insert(nodeStatus);
                jsonEntity.setJsonContent(nodeStatus.getJsonStatus());
            } catch (DataIntegrityViolationException e) {
                log.warn("记录已存在");
            }
        } else {
            // 如果查询到记录，直接更新 jsonEntity 的 jsonContent
            jsonEntity.setJsonContent(jsonStatus);
        }

        return jsonEntity;
    }

    @Override
    public void saveJsonEntity(JsonEntity jsonEntity) {
        studyTreeJsonMapper.insert(jsonEntity);
    }

    @Override
    public TagEntity getOrCreateTag(String tagName) {
        // Try to find an existing tag
        QueryWrapper<TagEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag_name", tagName);
        TagEntity tagEntity = studyTreeTagMapper.selectOne(queryWrapper);

        // If not found, create a new tag
        if (tagEntity == null) {
            tagEntity = new TagEntity();
            tagEntity.setTagName(tagName);
            studyTreeTagMapper.insert(tagEntity);
        }

        return tagEntity;
    }
    @Override
    public void saveJsonTagEntity(JsonTagEntity jsonTagEntity) {
        studyTreeJsonTagMapper.insert(jsonTagEntity);
    }



    /**
     * 为特定用户存储所有 JSON 的副本
     * @param userId 用户的ID
     */
    @Override
    public void storeJsonCopiesForUser(String userId) {
        // 获取所有的JsonEntity
        List<JsonEntity> jsonEntityList = studyTreeJsonMapper.selectList(null);

        // 遍历所有的JsonEntity，并为当前用户存储副本
        for (JsonEntity jsonEntity : jsonEntityList) {
            StudyTreeJsonNodeStatus nodeStatus = new StudyTreeJsonNodeStatus();
            nodeStatus.setId(UUID.randomUUID().toString()); // 生成随机 ID
            nodeStatus.setUserId(userId); // 设置用户ID
            nodeStatus.setJsonId(jsonEntity.getId()); // 使用JsonEntity的ID
            nodeStatus.setJsonStatus(jsonEntity.getJsonContent()); // 使用JsonEntity的jsonContent作为jsonStatus
            // 将数据插入到数据库
            studyTreeJsonNodeStatusMapper.insert(nodeStatus);
        }
    }
    /**
     * 根据 userId 和 jsonId 更新 jsonStatus
     */
    @Transactional
    @Override
    public void updateJsonStatus(UpdateJsonStatusRequest updateJsonStatusRequest) {
        String userId = UserContext.getUserId();
        Long jsonId=updateJsonStatusRequest.getJsonId();
        String jsonStatus=updateJsonStatusRequest.getJsonStatus();
        studyTreeJsonNodeStatusMapper.updateJsonStatus(userId, jsonId, jsonStatus);
    }
}
